import json

from django.shortcuts import render

# Create your views here.


from django.http import JsonResponse
from django.contrib.auth.models import User
from django.contrib.auth import authenticate



def register_user(request):

    if request.method == 'POST':
        data = json.loads(request.body.decode('utf-8'))
        username = data.get('username')
        password = data.get('password')
        print(username, password)
        if username and password:
            if User.objects.filter(username=username).exists():
                return JsonResponse({'code': 400, 'msg': {'status': 'false', 'username': username, 'password': password}})
            user = User(username=username, password=password)
            user.save()
            return JsonResponse({'code': 200, 'msg': {'status': 'true', 'username': username, 'password': password}})
        else:
            return JsonResponse({'code': 400, 'msg': {'status': 'false', 'username': None, 'password': None}})
    else:
        return JsonResponse({'code': 400, 'msg': {'status': 'false', 'username': 404, 'password': 404}})


def login_user(request):
    if request.method == 'GET':
        username = request.GET.get('username')
        password = request.GET.get('password')
        print(username, password)
        user = User.objects.filter(username=username, password=password)
        if user is not None:
            return JsonResponse({'code': 200, 'msg': {'status': True, 'username': username}})
        else:
            return JsonResponse({'code': 400, 'msg': {'status': False, 'username': username,}})
    else:
        return JsonResponse({'code': 400, 'msg': {'status': False, 'username': 'null'}})